package com.waqu.common.utils.security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;

/**
 * @Title Encryption.java
 * @Package com.waqu.common.utils.security
 * @author Administrator
 * @date 2015年6月15日 下午6:51:49
 * @version V1.0
 */
public class EncryptionTools {

	private static MessageDigest SHA256Digest = null, MD5Digest = null, SHA1Digest = null;

	private static MessageDigest getInstance(String algorithm, MessageDigest digest) throws Exception {
		if (null == digest)
			digest = MessageDigest.getInstance(algorithm);
		return digest;
	}

	public static String SHA256(String arg0) {
		try {
			SHA256Digest = getInstance("SHA-256", SHA256Digest);
			return encryption(arg0, SHA256Digest, true);
		} catch (Exception e) {
			return null;
		}
	}

	public static String MD5(String arg0) {
		return MD5(arg0, true);
	}
	
	public static String MD5(String arg0, boolean isUpper) {
		try {
			MD5Digest = getInstance("MD5", MD5Digest);
			return encryption(arg0, MD5Digest, isUpper);
		} catch (Exception e) {
			return null;
		}
	}

	public static String SHA1(String arg0) {
		try {
			SHA1Digest = getInstance("SHA-1", SHA1Digest);
			return encryption(arg0, SHA1Digest, true);
		} catch (Exception e) {
			return null;
		}
	}

	private static String encryption(String arg0, MessageDigest digest, boolean isUpper) throws UnsupportedEncodingException {
		String tmp = null;
		StringBuffer sb = new StringBuffer();
		for (byte b : digest.digest(arg0.getBytes("UTF-8"))) {
			tmp = Integer.toHexString(b & 0xFF);
			sb.append(tmp.length() == 1 ? "0" + tmp : tmp);
		}
		if(isUpper){
			return sb.toString().toUpperCase();
		}else{
			return sb.toString();
		}
	}

}
